<template>
  <a-form-model ref="form" :model="form" :rules="rules" @submit="onSubmit" class="main account-form-login" style="width: 320px">
    <a-form-model-item prop="phone">
      <a-input v-model="form.phone" allowClear size="large" placeholder="登录账号" :maxLength="11" autocomplete="off">
        <a-icon slot="prefix" type="user" />
      </a-input>
    </a-form-model-item>
    <a-form-model-item prop="passWord">
      <a-input-password v-model="form.passWord" allowClear size="large" placeholder="登录密码" :maxLength="32" autocomplete="off">
        <a-icon slot="prefix" type="lock" />
      </a-input-password>
    </a-form-model-item>
    <a-form-model-item>
      <a-checkbox v-model="form.auto">七天内自动登录</a-checkbox>
      <router-link :to="{ name: 'Register' }" class="forge-password" style="float: right">商家注册</router-link>
    </a-form-model-item>
    <a-form-model-item>
      <a-button block size="large" type="primary" html-type="submit" :loading="loading">立即登录</a-button>
    </a-form-model-item>
  </a-form-model>
</template>

<script>
import { mapActions } from 'vuex'
import { LoginForm } from '@/api/store'
export default {
  data() {
    return {
      form: {},
      loading: false, // 登录按钮状loading状态
      rules: {
        phone: [{ required: true, whitespace: true, message: '请输入登录账号', trigger: 'blur' }],
        passWord: [
          { required: true, whitespace: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, message: '密码最少设置6位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions(['SetLogin']),
    //立即登录
    onSubmit(e) {
      e.preventDefault()
      this.$refs.form.validate(valid => {
        if (!valid) return false
        const { $message, SetLogin, form } = this
        this.loading = true
        LoginForm(form)
          .then(res => {
            SetLogin(res)
            $message.success('登录成功')
            this.$router.replace({ name: this.$route.query?.goto ?? 'Home' })
          })
          .catch(err => {
            $message.error(err)
          })
          .finally(() => {
            this.loading = false
          })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.account-form-login {
  .avatar {
    cursor: pointer;
  }
  .ant-input-prefix {
    i {
      color: rgba(0, 0, 0, 0.25); //输入框前缀图标
    }
  }
  .ant-btn[type='button'] {
    font-size: 14px;
  }
}
</style>
